package com.p7.framework.permission.shiro.session;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionContext;
import org.apache.shiro.session.mgt.SessionFactory;
import org.apache.shiro.web.session.mgt.DefaultWebSessionContext;

/**
 * session 工厂
 * @author Yangzhen
 * @Description
 * @date 2019-02-13 15:47
 **/
public class ClientSessionFactory implements SessionFactory {

	private static final String LOCAL_IP = "127.0.0.1";

	/**
	 * 登录时调用此方法创建session
	 *
	 * @param sessionContext
	 * @return
	 * @Title: createSession
	 * @date 2019年2月16日 下午2:01:48
	 * @author yz
	 * @see org.apache.shiro.session.mgt.SessionFactory#createSession(org.apache.shiro.session.mgt.SessionContext)
	 */
	@Override
	public Session createSession(SessionContext sessionContext) {
		ClientSession session = new ClientSession();
		session.setHost(getIpAddress((HttpServletRequest) sessionContext.get(DefaultWebSessionContext.class.getName() + ".SERVLET_REQUEST")));
		return session;
	}

	/**
	 * 获取IP地址
	 *
	 * @param request
	 * @return
	 * @Title: getIpAddress
	 * @date 2019年2月16日 下午2:10:21
	 * @author yz
	 */
	public static String getIpAddress(HttpServletRequest request) {

		String ip = request.getHeader("X-Forwarded-For");
		if (StringUtils.isBlank(ip) || (ip.equalsIgnoreCase(LOCAL_IP)) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isBlank(ip) || (ip.equalsIgnoreCase(LOCAL_IP)) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isBlank(ip) || (ip.equalsIgnoreCase(LOCAL_IP)) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

}
